import { onMounted, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { getCategorySubGoods } from '@/apis/goods.js'

export function useSubCategory() {
  const route = useRoute()
  const categoryId = ref('')

  const categorySubGoods = ref({})

  onMounted(async () => {
    if (!categoryId.value) {
      categoryId.value = route.params.id
      categorySubGoods.value = await getCategorySubGoods(categoryId.value)
    }
  })

  watch(
    () => route.params.id,
    async (newId, oldId) => {
      categoryId.value = newId
      categorySubGoods.value = await getCategorySubGoods(newId)
    },
  )
  return {
    categorySubGoods,
    categoryId,
  }
}
